package com.example.securitysmslogin.security;

import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * 短信登陆鉴权 Provider，要求实现 AuthenticationProvider 接口
 */
public class SmsCodeAuthenticationProvider implements AuthenticationProvider {
    private UserDetailsService userDetailsService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        SmsCodeAuthenticationToken authenticationToken = (SmsCodeAuthenticationToken) authentication;
        //获取手机号码和验证码
        String mobile = determineMobile(authentication);
        String smsCode = (String) authenticationToken.getCredentials();
        checkSmsCode(mobile, smsCode);

        UserDetails userDetails = userDetailsService.loadUserByUsername(mobile);
        // 此时鉴权成功后，应当重新 new 一个拥有鉴权的 authenticationResult 返回
        return createSuccessAuthentication(userDetails, authentication, userDetails);
    }

    /**
     * 这个方法照抄AbstractUserDetailsAuthenticationProvider中的createSuccessAuthentication
     * @param principal
     * @param authentication
     * @param user
     * @return
     */
    private SmsCodeAuthenticationToken createSuccessAuthentication(Object principal, Authentication authentication,
                                               UserDetails user) {
        // Ensure we return the original credentials the user supplied,
        // so subsequent attempts are successful even with encoded passwords.
        // Also ensure we return the original getDetails(), so that future
        // authentication events after cache expiry contain the details
        SmsCodeAuthenticationToken authenticationResult =
                new SmsCodeAuthenticationToken(principal, authentication.getCredentials(), user.getAuthorities());
        authenticationResult.setDetails(authentication.getDetails());
        return authenticationResult;
    }

    /**
     * 这行代码照抄了AbstractUserDetailsAuthenticationProvider中的determineUsername
     * @param authentication
     * @return
     */
    private String determineMobile(Authentication authentication) {
        return (authentication.getPrincipal() == null) ? "NONE_PROVIDED" : authentication.getName();
    }

    private void checkSmsCode(String mobile, String smsCode) {
        //从session中获取保存的手机号码和验证码
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        final HttpSession session = request.getSession();
        String sessionMobile = (String) session.getAttribute("mobile");
        String sessionCode = (String) session.getAttribute("smsCode");
        if(sessionCode == null) {
            throw new BadCredentialsException("未检测到申请验证码");
        }
        if(!sessionMobile.equals(mobile)) {
            throw new BadCredentialsException("申请的手机号码与登录手机号码不一致");
        }
        if(!sessionCode.equals(smsCode)) {
            throw new BadCredentialsException("验证码错误");
        }
        //校验检查都通过后，将验证码删除
        session.removeAttribute("smsCode");
    }

    @Override
    public boolean supports(Class<?> authentication) {
        // 判断 authentication 是不是 SmsCodeAuthenticationToken 的子类
        return SmsCodeAuthenticationToken.class.isAssignableFrom(authentication);
    }

    public UserDetailsService getUserDetailsService() {
        return userDetailsService;
    }

    public void setUserDetailsService(UserDetailsService userDetailsService) {
        this.userDetailsService = userDetailsService;
    }
}
